package net.easyjava.tools.http;

import net.easyjava.tools.BaseTools;
import net.easyjava.tools.http.bean.ImageBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by wxnacy on 16/2/2.
 */
public class HttpImageTools extends BaseTools {
    private static Logger logger = LoggerFactory.getLogger(HttpImageTools.class);

    /**
     * 从图片地址获取图片实例类
     * @param ImgUrl
     * @return
     */
    public static ImageBean getImageFromUrl(String ImgUrl){
        URL url = null;
        ImageBean imageBean = new ImageBean(ImgUrl);
        try {
            url = new URL(ImgUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            String type = connection.getContentType();
            String suffix="";
            if ((type.equals("image/pjpeg") || type.equals("image/jpeg")) ) {
                suffix = ".jpg";
            }else if(type.equals("image/png")){
                suffix = ".png";
            }else if(type.equals("image/gif")){
                suffix = ".gif";
            }else if(type.equals("image/bmp")){
                suffix = ".bmp";
            }
            imageBean.setType(type);
            imageBean.setSuffix(suffix);
            imageBean.setInputStream(connection.getInputStream());
            imageBean.setSize(connection.getContentLengthLong());

            BufferedImage bi = ImageIO.read(imageBean.getInputStream());
            imageBean.setWidth(bi.getWidth());
            imageBean.setHeight(bi.getHeight());


            return imageBean;
        } catch (Exception e) {
            logger.error(e.getMessage(),e.fillInStackTrace());
            return null;
        }

    }


    public static void main(String[] args) {
        System.out.println("getImageFromUrl(\"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201601/29/00B8CFB5FE8ABE1113B444FF74EC78C0.gif\").toString() = " + getImageFromUrl("http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201601/29/00B8CFB5FE8ABE1113B444FF74EC78C0.gif").toString());
    }
}
